package permission

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/sms"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminSmsCaptchaLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminSmsCaptchaLogic - 发送短信验证码
func NewAdminSmsCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminSmsCaptchaLogic {
	return &AdminSmsCaptchaLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminSmsCaptchaLogic) AdminSmsCaptcha(req *types.AdminSmsCaptchaRequest) error {
	userDao := permission.NewAdminUserDao(l.ctx, l.svcCtx)

	// 查询管理员账号
	cond := make([]predicate.AdminUser, 0, 2)
	cond = append(cond, adminuser.AdminUserUsernameEQ(req.Phone))
	cond = append(cond, adminuser.IsDeleteEQ(bizadmin.NotDelete))
	userInfo, _ := userDao.AdminUserFirst(cond)

	// 校验用户
	if userInfo != nil && userInfo.AdminUserStatus == bizadmin.StatusDisable {
		return xerr.ErrCodeMsg(xerr.ServerAdminAccountBanned, "用户已被禁用")
	}

	//生成4位随机验证码
	captcha := common.GenerateCaptcha()

	// 保存验证码，有效期5分钟
	err := l.svcCtx.BizRedis.Setex(constant.HzAdminLoginCaptchaKey+req.Phone, captcha, 6*60)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("redis保存验证码失败：%v", err.Error()))
	}

	// 华瑞云短信
	//hry, _ := sms.NewHrySmsService()
	tencent, _ := sms.NewTencentSmsService()
	//msg := fmt.Sprintf("【慧赚生活】%s为您的登录验证码，请于5分钟内填写，如非本人操作，请忽略本短信。", captcha)

	//发送短信
	//err = hry.SendMessage(req.Phone, msg, l.svcCtx.Config.Env)
	err = tencent.Send(req.Phone, captcha)
	if err != nil {
		l.Errorf("send sms error: %v", err)
		l.svcCtx.BizRedis.Del(constant.HzAdminLoginCaptchaKey + req.Phone)
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("发送短信失败：%v", err.Error()))
	}

	l.Infof("验证码为: %v", captcha)
	return nil
}
